package com.gf.framework.redis.aspect;

import com.gf.framework.redis.annotation.CacheExpire;
import com.gf.framework.redis.core.CacheExpireHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


/**
 * 缓存失效时间Aspect
 *
 */
@Slf4j
@Aspect
// 设置高优先级，在cacheable等执行前后环绕
@Order(-1)
@Component
public class CacheExpireAspect {

    /**
     * 设置方法对应的缓存过期时间
     */
    @Around("@annotation(com.gf.framework.redis.annotation.CacheExpire)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        CacheExpire cacheExpire = method.getAnnotation(CacheExpire.class);
        //设置失效时间
        CacheExpireHolder.set(cacheExpire.expire(), cacheExpire.timeUnit(), cacheExpire.range());

        try {
            return joinPoint.proceed();
        }
        catch (Throwable throwable) {
            throw throwable;
        }
        finally {
            CacheExpireHolder.remove();
        }
    }

}
